package com.sqx.modules.reward.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.Result;
import com.sqx.modules.reward.entity.Reward;
import com.sqx.modules.reward.dao.RewardDao;
import com.sqx.modules.reward.service.RewardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author www.javacoder.top
 * @since 2023-01-16
 */
@Service
public class RewardServiceImpl extends ServiceImpl<RewardDao, Reward> implements RewardService {


    @Override
    public Result saveReward(Reward reward) {
        QueryWrapper<Reward> wrapper = new QueryWrapper<Reward>().eq("num", reward.getNum());
        if (reward.getRewardId() != null) {
            wrapper.ne("reward_id", reward.getRewardId());
        }
        Integer count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            return Result.error("不能添加重复的奖励单数");
        }
        if (reward.getRewardId() != null) {
            return Result.upStatus(baseMapper.updateById(reward));
        } else {
            reward.setCreateTime(LocalDateTime.now());
            return Result.upStatus(baseMapper.insert(reward));
        }

    }

    @Override
    public IPage<Reward> getRewardList(Integer page, Integer limit, Reward reward) {
        Page<Reward> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(reward).orderByAsc("sort"));
    }
}
